<?php

namespace app\admin\model\yunfood;

use think\Exception;

/**
 * 订单
 */
class Order extends \addons\yunfood\model\Order
{
    // 自定义初始化
    protected static function init()
    {
        Order::beforeWrite(function ($record) {
            $changed = $record->getChangedData();
            if (isset($changed['status']) &&
                in_array($changed['status'], [self::STATUS_HAS_CANCEL, self::STATUS_HAS_TIMEOUT])) {
                if ($record->origin['status'] != self::STATUS_WAIT_PAY) {
                    throw new Exception('当前状态不能进行此操作');
                }
            }

            return true;
        });

        Order::afterWrite(function ($record) {
            $changed = $record->getChangedData();
            if (isset($changed['status']) &&
                $record->origin['status'] == self::STATUS_WAIT_PAY &&
                in_array($changed['status'], [self::STATUS_HAS_CANCEL, self::STATUS_HAS_TIMEOUT])) {
                // 取消订单
                Order::cancelOrder($record->order_no, $changed['status'], false);
            }

            return true;
        });
    }
}
